import { useEffect, useRef, useState } from 'react';

function useLoading(loading, effects, { delay = 300, max = 0 } = {}) {
  const ref = useRef({ timer: null, status: {} });
  // 显示次数
  const times = useRef(0);
  const isStop = useRef(false);

  // 是否在 loading
  const [showLoading, setShowLoading] = useState(false);

  const setLoadingFalse = () => {
    setShowLoading(false);

    // 停止不再触发
    if (max > 0 && times.current >= max) {
      isStop.current = true;
    }
  };

  const setLoadingTrue = () => {
    if (showLoading) {
      return;
    }

    setShowLoading(true);

    // 计数器 +1
    times.current += 1;
  };

  useEffect(() => {
    // 清除上次的定时器
    clearTimeout(ref.current.timer);
    ref.current.timer = null;

    // 超过次数了就不再显示了
    if (isStop.current) {
      return;
    }

    let loadingStatus = {};

    // 判断是否存在loading
    effects.forEach((key) => {
      if (loading.effects[key]) {
        // 更新上次loading 时间
        ref.current.status[key] = Date.now();

        loadingStatus.isLoading = true;
      }
    });

    // 判断是否需要延迟关闭loading
    if (!loadingStatus.isLoading) {
      effects.forEach((key) => {
        // 检测 loadingStatus
        let len = Date.now() - (ref.current.status[key] ?? 0);
        if (len < delay) {
          if (!loadingStatus.len || delay - len > loadingStatus.delay) {
            loadingStatus = { isLoading: false, key, delay: delay - len };
          }
        }
      });
    }

    // 正在 loading
    if (loadingStatus.isLoading) {
      setLoadingTrue();
    }
    // 需要延迟关闭loading
    else if (loadingStatus.key) {
      setLoadingTrue();

      ref.current.timer = setTimeout(() => {
        setLoadingFalse();
      }, loadingStatus.delay);
    }
    // 关闭loading
    else {
      setLoadingFalse();
    }
  }, [
    loading,
    // 数组需要string下
    effects.join('|'),
    delay,
  ]);

  return showLoading;
}

export { useLoading };
